package com.pingan.glue.gluegame.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pingan.glue.gluegame.exception.BusinessException;
import com.pingan.glue.gluegame.response.ResponseCode;
import com.pingan.glue.gluegame.response.ResponseData;
import com.pingan.glue.gluegame.response.ResponseResult;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class GlueGameClient {
    private final static Logger LOGGER = LoggerFactory.getLogger(GlueGameClient.class);
    private final MediaType MEDIA_JSON = MediaType.parse("application/json; charset=utf-8");

    private OkHttpClient httpClient;

    @Value("glue.game.aip.connect.time.out")
    private String connectTimeOut; //30
    @Value("glue.game.aip.read.time.out")
    private String readTimeOut; //30
    @Value("glue.game.aip.write.time.out")
    private String writeTimeOut; //30

    public GlueGameClient() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30,TimeUnit.SECONDS)
                .retryOnConnectionFailure(true);
        httpClient = builder.build();
    }

    public JSONObject get(String url){
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        return doHttpRequest(request);
    }

    public JSONObject post(String url, String accretToken, Map<String,Object> params){
        String jsonString = JSON.toJSONString(params);
        RequestBody requestBody = RequestBody.create(MEDIA_JSON, jsonString);
        Request request = new Request.Builder()
                .url(url+accretToken)
                .post(requestBody)
                .build();
        return doHttpRequest(request);
    }




    /**
     * HTTP请求
     *
     * @param request
     * @return
     * @throws BusinessException
     */
    protected JSONObject doHttpRequest(Request request) throws BusinessException {
        try {
            Response response = httpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                String result = response.body().string();
                response.close();
                return JSONObject.parseObject(result);
            }
            return new JSONObject();

        } catch (IOException e) {
            LOGGER.error("doHttpRequest exception:{}", e.getMessage());
            throw new BusinessException("", e.getMessage());
        }
    }

    public String getString(String url){
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        return doHttpRequestToString(request);
    }

    /**
     * HTTP请求
     *
     * @param request
     * @return
     * @throws BusinessException
     */
    protected String doHttpRequestToString(Request request) throws BusinessException {
        try {
            Response response = httpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                String result = response.body().string();
                response.close();
                return result;
            }
            return "";

        } catch (IOException e) {
            LOGGER.error("doHttpRequest exception:{}", e.getMessage());
            throw new BusinessException("", e.getMessage());
        }
    }


}
